import { AppCTX } from "../../types/koaExtend";
import {
  getOrderBySerialNumber,
  placeOrder,
  repayOrder,
  cancelOrder,
  pickOrderByC,
  receiveOrder,
  listOrderItemsForC,
  listOrderItemsForS,
} from "../../service/orderService";
import { createPayment } from "../../service/paymentService";
import { getBrand } from "../../service/brandService";
import pageMW from "../../middleware/pager";
import Router from "koa-router";
import { isUndefined, randomNumber } from "mmb";
import { isSearchTerm } from "../../bg-enums/searchTerm";
import OrderStatus, { isOrderStatus } from "../../bg-enums/orderStatus";
const router = new Router();

// 订单再次支付
router.post(
  "/usr/order/:orderSerialNumber/repay",
  async (ctx: AppCTX, next) => {
    const { orderSerialNumber } = ctx.params;
    const { userId } = ctx;

    const transactionInfo = await repayOrder({ orderSerialNumber, userId });

    ctx.body = {
      transactionInfo,
    };
  }
);

// 订单下单(创建订单+支付)
router.post("/usr/order/place", async (ctx: AppCTX, next) => {
  const {
    brandId,
    activityId,
    shareUserId,
    deliveryMode,
    remark,
    shippingAddress,
    shippingFee,
    productAmount,
    amount,
    warehouseId,
    details,
    awardId,
  } = ctx.request.body;
  const { userId, userOpenId } = ctx;
  let { order, transactionInfo } = await placeOrder({
    brandId,
    activityId,
    userId,
    userOpenId,
    shareUserId,
    deliveryMode,
    remark,
    shippingAddress,
    shippingFee,
    productAmount,
    amount,
    warehouseId,
    details,
    awardId,
  });
  ctx.body = {
    order,
    transactionInfo,
  };
});

// 订单取消
router.put(
  "/usr/order/:orderSerialNumber/cancel",
  async (ctx: AppCTX, next) => {
    const { orderSerialNumber } = ctx.params;
    const { cancelReason } = ctx.request.body;
    const { userId } = ctx;
    const cancelRet = await cancelOrder({
      orderSerialNumber,
      userId,
      cancelReason,
    });
    ctx.body = cancelRet;
  }
);

// 用户确认提货
router.put("/usr/order/:orderSerialNumber/pick", async (ctx: AppCTX, next) => {
  const { orderSerialNumber } = ctx.params;
  const { userId } = ctx;
  const pickRet = await pickOrderByC({ orderSerialNumber, userId });
  ctx.body = pickRet;
});

// 用户确认收货
router.put(
  "/usr/order/:orderSerialNumber/receive",
  async (ctx: AppCTX, next) => {
    const { orderSerialNumber } = ctx.params;
    const { userId } = ctx;
    const order = await receiveOrder({ orderSerialNumber, userId });
    ctx.body = order;
  }
);

// 获取用户的订单列表
router.get("/usr/orders", pageMW, async (ctx: AppCTX, next) => {
  const { userId, limit, offset, ts } = ctx;
  const { isAll, orderStatus } = ctx.query;
  let arrOrderStatus: OrderStatus[] = [];
  if (!isUndefined(orderStatus)) {
    for (let ps of orderStatus.split(",")) {
      if (!isOrderStatus(ps)) {
        ctx.throw(400, "orderStatus invalid");
      }
      arrOrderStatus.push(ps);
    }
  }

  const { total, items } = await listOrderItemsForC({
    userId,
    isAll: isAll === "true",
    orderStatuses: arrOrderStatus,
  }, {
    limit,
    offset,
    ts,
  });
  ctx.body = {
    total,
    rows: items,
  };
});

// 获取用户的推广订单列表
router.get("/usr/bonusOrders", pageMW, async (ctx: AppCTX, next) => {
  const { userId, limit, offset, ts } = ctx;
  const { searchTerm, searchValue, isAll, orderStatus } = ctx.query;

  let arrOrderStatus: OrderStatus[] = [];
  if (!isUndefined(orderStatus)) {
    for (let ps of orderStatus.split(",")) {
      if (!isOrderStatus(ps)) {
        ctx.throw(400, "orderStatus invalid");
      }
      arrOrderStatus.push(ps);
    }
  }
  if (!isUndefined(searchTerm) && !isSearchTerm(searchTerm)) {
    ctx.throw(400, "invalid searchTerm");
  }

  const { total, items } = await listOrderItemsForS(
    {
      userId,
      isAll: isAll === "true",
      orderStatuses: arrOrderStatus,
      searchTerm,
      searchValue,
    },
    { limit, offset, ts }
  );
  ctx.body = {
    total,
    rows: items,
  };
});

// 获取订单详情(用户视角)
router.get("/usr/order/:orderSerialNumber", async (ctx: AppCTX, next) => {
  const { orderSerialNumber } = ctx.params;
  const { userId } = ctx;

  const order = await getOrderBySerialNumber(orderSerialNumber);
  if (isUndefined(order)) {
    ctx.throw("invalid orderSerialNumber");
  }

  // 判断订单用户所属:userId是否是order.userId
  if (userId !== order.userId) {
    ctx.throw(403, "no permission to access resource");
  }

  // switch (order.orderStatus) {
  //   case "created":
  //     break;
  //   case "pending":
  //     break;
  //   case "payed":
  //     break;
  //   case "delivered":
  //     break;
  //   case "prepared":
  //     break;
  //   case "finished":
  //     break;
  //   case "closed":
  //   default:
  //     break;
  // }

  ctx.body = order;
});

export default router;
